package com.siwei.mes.common.JPush;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.siwei.mes.common.JPush.config.JPushConfig;
import com.siwei.mes.common.JPush.config.PushMessage;
import com.siwei.mes.common.util.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 极光推送clinent
 *
 * @author linzi
 * @create 2022-01-18 13:52
 */
@SuppressWarnings("ALL")
@Slf4j
@Service
public class JPushUtil {
    @Resource
    private JPushConfig jPushConfig;

    // 设置好账号的app_key和masterSecret是必须的   这里是本地调试的时候设置的
    private static String APP_KEY = "23a4c1ff35935f6ae14d6619";
    private static String MASTER_SECRET = "70c79d814d56f346ec910c4e";

    /**
     * 极光推送 Android
     *
     * @param pushMessage
     */
    public PushResult pushAndroid(PushMessage pushMessage) {
        //创建JPushClient
//        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        JPushClient jpushClient = new JPushClient(jPushConfig.getSecret(), jPushConfig.getAppKey());
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())//指定android平台的用户
                .setAudience(Audience.all())//你项目中的所有用户
//                .setAudience(Audience.alias(pushMessage.getAlias()))//设置别名发送,单发，点对点方式
//                .setAudience(Audience.tag("tag1"))//设置按标签发送，相当于群发
//                .setAudience(Audience.registrationId(pushMessage.getRegistrationId()))//registrationId指定用户

                .setNotification(Notification.android(pushMessage.getMessage(), jPushConfig.getTitle(), MapUtils.objectToMap(pushMessage.getPushMsgDto())))  //发送内容
                .setOptions(Options.newBuilder().setApnsProduction(jPushConfig.getApnsProduction()).setTimeToLive(7200).build())
                // apnProduction指定开发环境 true为生产模式 false 为测试模式 (android不区分模式,ios区分模式) 不用设置也没关系
                // TimeToLive 两个小时的缓存时间
                .setMessage(Message.content(pushMessage.getMessage()))//自定义信息
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
            return pu;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 极光推送 ios
     *
     * @param pushMessage
     */
    public PushResult pushIOS(PushMessage pushMessage) {
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(jPushConfig.getSecret(), jPushConfig.getAppKey());
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())//ios平台的用户
                .setAudience(Audience.all())//所有用户
                .setAudience(Audience.alias(pushMessage.getAlias()))//别名推送
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(pushMessage.getMessage())
                                .setBadge(+1)
                                .setSound("happy")//这里是设置提示音(更多可以去官网看看)
                                .addExtras(MapUtils.objectToMap(pushMessage.getPushMsgDto()))
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(jPushConfig.getApnsProduction()).build())
                .setMessage(Message.newBuilder().setMsgContent(pushMessage.getMessage()).addExtras(MapUtils.objectToMap(pushMessage)).build())//自定义信息
                .build();

        try {
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
            return pu;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 极光推送  所有平台  单个设备id
     *
     * @param pushMessage
     */
    public PushResult pushAll(PushMessage pushMessage) {
        if (StringUtils.isBlank(pushMessage.getAlias())) {
            log.info("推送别名为空：{}", pushMessage.getPushMsgDto());
            return null;
        }
        //创建JPushClient
//        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        JPushClient jpushClient = new JPushClient(jPushConfig.getSecret(), jPushConfig.getAppKey());
        //创建option
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())  //所有平台的用户
                .setAudience(Audience.alias(pushMessage.getAlias()))//别名推送
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder() //发送ios
                                .setAlert(pushMessage.getMessage()) //消息体
                                .setBadge(+1)
                                .setSound("happy") //ios提示音
                                .addExtras(MapUtils.objectToMap(pushMessage.getPushMsgDto())) //附加参数
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder() //发送android
                                .addExtras(MapUtils.objectToMap(pushMessage.getPushMsgDto())) //附加参数
                                .setAlert(pushMessage.getMessage()) //消息体
                                .build())
                        .build())
                //指定开发环境 true为生产模式 false 为测试模式 (android不区分模式,ios区分模式)
                .setOptions(Options.newBuilder().setApnsProduction(jPushConfig.getApnsProduction()).build())
//                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                //自定义信息
                .setMessage(Message.newBuilder().setMsgContent(pushMessage.getMessage()).addExtras(MapUtils.objectToMap(pushMessage)).build())
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            log.info("极光推送结果>>>>>>>>>>>>>>>code: {}, msgId:{}", pu.statusCode, pu.msg_id);
            if (pu.error != null) {
                log.info("极光推送结果>>>>>>>>>>>>>>>message:{}, code:{}", pu.error.getMessage(), pu.error.getCode());
            }
            return pu;
        } catch (Exception e) {
            log.error("{}", e);
        }
        return null;
    }

    /**
     * 极光推送 所有平台  多个设备id
     *
     * @param pushMessage
     * @return
     */
    public PushResult pushAllList(PushMessage pushMessage) {
        if (pushMessage.getAliasList().size() == 0) {
            log.info("推送别名为空：入参：{}", JSON.toJSON(pushMessage));
            return null;
        }
        //创建JPushClient
//        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        JPushClient jpushClient = new JPushClient(jPushConfig.getSecret(), jPushConfig.getAppKey());
        //创建option
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())  //所有平台的用户
                .setAudience(Audience.alias(pushMessage.getAliasList()))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder() //发送ios
                                .setAlert(pushMessage.getMessage()) //消息体
                                .setBadge(+1)
                                .setSound("happy") //ios提示音
                                .addExtras(MapUtils.objectToMap(pushMessage.getPushMsgDto())) //附加参数
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder() //发送android
                                .addExtras(MapUtils.objectToMap(pushMessage.getPushMsgDto())) //附加参数
                                .setAlert(pushMessage.getMessage()) //消息体
                                .build())
                        .build())
                //指定开发环境 true为生产模式 false 为测试模式 (android不区分模式,ios区分模式)
                .setOptions(Options.newBuilder().setApnsProduction(jPushConfig.getApnsProduction()).build())
                //自定义信息
                .setMessage(Message.newBuilder().setMsgContent(pushMessage.getMessage()).addExtras(MapUtils.objectToMap(pushMessage)).build())
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            log.info("极光推送结果>>>>>>>>>>>>>>>code: {}, msgId:{}", pu.statusCode, pu.msg_id);
            if (pu.error != null) {
                log.info("极光推送结果>>>>>>>>>>>>>>>message:{}, code:{}", pu.error.getMessage(), pu.error.getCode());
            }
            return pu;
        } catch (Exception e) {
            log.error("极光推送失败，入参：{}，原因：{}", JSON.toJSON(pushMessage), e.getMessage(), e);
        }
        return null;
    }


    public static void main(String[] args) {
        JPushUtil jPushUtil = new JPushUtil();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setAlias("13701637629");
        pushMessage.setMessage(String.format("%s更新了%s，快来看看，让我们一步步发现客户最美、最真实的样子", "测试", "上海思伟"));
        PushResult pushResult = jPushUtil.pushAll(pushMessage);
        System.out.println(JSON.toJSONString(pushResult));
    }

}
